﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Protocol;
using MQTTnet.Packets;
using MQTTnet.Server;

namespace MQTTClientTest
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var mqttClientWrapper = new MqttClientWrapper();
            var publishStrategyManager = new PublishStrategyManager(mqttClientWrapper);

            try
            {
                // 连接到 MQTT 代理
                await mqttClientWrapper.ConnectAsync("localhost", 1883, "cxh", "cxh");
                Console.WriteLine("Connected to MQTT broker.");

                // 订阅主题
                await mqttClientWrapper.SubscribeBulkAsync(new List<string> { "test/topic1", "test/topic2", "timed_bulk_topic/#" });
                Console.WriteLine("Subscribed to topics: test/topic1, test/topic2, timed_bulk_topic/+");

                //// 数据变化时发布策略
                //publishStrategyManager.OnDataChanged("test", "value1");

                //// 数据变化时批量发布策略
                //var dataPairs = new List<(string tag, string value)>
                //{
                //    ("test1", "value1"),
                //    ("test2", "value2")
                //};
                //await publishStrategyManager.OnDataChangedBulk(dataPairs);

                //// 阈值发布策略
                //publishStrategyManager.OnThresholdReached("test", "2", 1, (x, y) => x.CompareTo(y));

                //// 时间窗口发布策略
                //publishStrategyManager.OnTimeWindow("test", "value1", TimeSpan.FromMinutes(5));

                //// 累积发布策略
                //for (int i = 1; i <= 10; i++)
                //{
                //    await publishStrategyManager.OnAccumulation("test", i.ToString());
                //}

                //// 优先级发布策略
                //publishStrategyManager.SetPriority("test1", "value1", 3);
                //publishStrategyManager.SetPriority("test2", "value2", 1);
                //await publishStrategyManager.OnPriorityPublish(2);

                // 定时发布策略
                publishStrategyManager.StartTimedPublish(TimeSpan.FromSeconds(1), "timed_topic", "timed_payload");

                // 生成 1000 个消息
                var timedMessages = new List<(string topic, string payload, MqttQualityOfServiceLevel qos, bool retain)>();
                for (int i = 0; i < 10000; i++)
                {
                    timedMessages.Add(($"t/{i}", $"{i}", MqttQualityOfServiceLevel.AtMostOnce, false));
                }

                publishStrategyManager.StartTimedPublishBulkParallel(TimeSpan.FromSeconds(60), timedMessages);


                // 定时批量发布策略
                //publishStrategyManager.StartTimedPublishBulk(TimeSpan.FromSeconds(20), timedMessages);

                Console.WriteLine("Started timed bulk publish of 1000 messages every 10 seconds.");

                Console.WriteLine("Press any key to stop timed publishing and exit...");
                Console.ReadKey();

                // 获取最近5秒内的数据
                var recentData = mqttClientWrapper.GetAllTags();

                // 获取最近1秒内的数据
                var veryRecentData = mqttClientWrapper.GetAllTags(TimeSpan.FromSeconds(1));

                Console.WriteLine("All tags and their values:");
                foreach (var kvp in recentData)
                {
                    Console.WriteLine($"{kvp.Key}: {kvp.Value}");
                }

                // 停止定时发布
                publishStrategyManager.StopTimedPublish();

                //// 获取特定标签的值
                //if (mqttClientWrapper.TryGetTagValue("test/topic1", out string value))
                //{
                //    Console.WriteLine($"Value for test/topic1: {value}");
                //}
                //else
                //{
                //    Console.WriteLine("test/topic1 not found in tag store.");
                //}

                //// 取消订阅主题
                //await mqttClientWrapper.UnsubscribeBulkAsync("test/topic1", "test/topic2");
                //Console.WriteLine("Unsubscribed from topics: test/topic1, test/topic2");

                //// 断开连接
                //await mqttClientWrapper.DisconnectAsync();
                //Console.WriteLine("Disconnected from MQTT broker.");

                //// 重复连接和断开操作
                //for (int i = 0; i < 3; i++)
                //{
                //    Console.WriteLine($"Attempting to connect (Attempt {i + 1})...");
                //    await mqttClientWrapper.ConnectAsync("localhost", 1883, "admin", "password");
                //    Console.WriteLine($"Connected to MQTT broker (Attempt {i + 1}).");

                //    // 执行一些操作
                //    publishStrategyManager.OnDataChanged("test", $"value{i + 1}");

                //    // 获取特定标签的值
                //    if (mqttClientWrapper.TryGetTagValue("test/topic1", out value))
                //    {
                //        Console.WriteLine($"Value for test/topic1: {value}");
                //    }
                //    else
                //    {
                //        Console.WriteLine("test/topic1 not found in tag store.");
                //    }

                //    // 取消订阅主题
                //    await mqttClientWrapper.UnsubscribeBulkAsync("test/topic1", "test/topic2");
                //    Console.WriteLine("Unsubscribed from topics: test/topic1, test/topic2");

                //    Console.WriteLine($"Attempting to disconnect (Attempt {i + 1})...");
                //    await mqttClientWrapper.DisconnectAsync();
                //    Console.WriteLine($"Disconnected from MQTT broker (Attempt {i + 1}).");
                //}
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
            }
            finally
            {
                // 确保停止定时发布
                publishStrategyManager.StopTimedPublish();

                // 确保断开连接
                try
                {
                    if (mqttClientWrapper.IsConnected)
                    {
                        await mqttClientWrapper.DisconnectAsync();
                        Console.WriteLine("Disconnected from MQTT broker in finally block.");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Failed to disconnect in finally block: {ex.Message}");
                }

                // 释放资源
                mqttClientWrapper.Dispose();
                Console.WriteLine("MqttClientWrapper disposed.");
            }
        }
    }
}